import React, { Component } from 'react'
import { connect } from 'react-redux'
import { asyncInitList, asyncDelListById, asyncAddListItem } from "../reducers/userReducer"
import { userModel } from '../model/userMode'
//dva  mobx
class User extends Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            username: "",
            userpwd: ""
        }

    }

    async componentDidMount() {
        if (!this.props.list.length) {
            this.props.asyncInitList();
        }

    }
    del = async (id: any) => {
        this.props.asyncDelListById(id);

    }
    add = () => {
        this.props.asyncAddListItem({
            username:this.state.username,
            userpwd:this.state.userpwd
        }).then((res:any)=>{
            alert(res.msg);

        })


    }

    render() {
        return (
            <div>
                <div>
                    用户名 <input type="text" value={this.state.username} onChange={(e) => {
                        this.setState({
                            username: e.target.value
                        })
                    }} />
                </div>
                <div>
                    密码 <input type="text" value={this.state.userpwd} onChange={(e) => {
                        this.setState({
                            userpwd: e.target.value
                        })
                    }} />
                </div>
                <button onClick={() => {
                    this.add();
                }}>新增</button>

                <div className='table'>
                    <div className='tr'>
                        <div className='td'>编号</div>
                        <div className="td">用户名</div>
                        <div className="td">密码</div>
                        <div className="td">操作</div>
                    </div>
                    {this.props.list.map((item: any) => (<div className='tr' key={item.id}>
                        <div className='td'>{item.id}</div>
                        <div className="td">{item.username}</div>
                        <div className="td">{item.userpwd}</div>
                        <div className="td" onClick={() => {
                            this.del(item.id)
                        }}>删除</div>
                    </div>))}
                </div>
            </div>
        )
    }
}

const mapStateToProps = (state: any) => ({
    list: state.userInfo.list
})

const mapDispatchToProps = {
    asyncInitList,
    asyncDelListById,
    asyncAddListItem
}

export default connect(mapStateToProps, mapDispatchToProps)(User)